<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

/**
*
* @package MediaLibrary
* @copyright 2009 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru);Rob de Cleen(rob@decleen.com)
* Homepage: http://www.joomlawebserver.com
* @version: 1.5.3 Basic $
*
**/

defined( '_VM_IS_BACKEND' ) or define( '_VM_IS_BACKEND', '1' );

include_once( dirname(__FILE__).'/compat.joomla1.5.php' );
$my=$GLOBALS['my'];

$css = $mosConfig_live_site.'/administrator/components/com_medialibrary/includes/medialibrary.css';

include_once ($mainframe->getPath('admin_html'));
include_once ($mainframe->getPath('class'));

require_once($mosConfig_absolute_path."/components/com_medialibrary/medialibrary.class.php");
require_once($mosConfig_absolute_path."/components/com_medialibrary/medialibrary_game.class.php");
require_once($mosConfig_absolute_path."/components/com_medialibrary/medialibrary_music.class.php");
require_once($mosConfig_absolute_path."/components/com_medialibrary/medialibrary_book.class.php");
require_once($mosConfig_absolute_path."/components/com_medialibrary/medialibrary_video.class.php");
require_once ($mosConfig_absolute_path."/components/com_medialibrary/medialibrary.class.lend.php");
require_once ($mosConfig_absolute_path."/components/com_medialibrary/medialibrary.class.lend_request.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_medialibrary/admin.medialibrary.class.ws.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_medialibrary/admin.medialibrary.class.impexp.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_medialibrary/admin.medialibrary.class.conf.php");



$GLOBALS['medialibrary_configuration'] = $medialibrary_configuration;
$GLOBALS['database'] = $database;
$GLOBALS['my'] = $my;
$GLOBALS['mosConfig_absolute_path'] = $mosConfig_absolute_path;
require_once ($mosConfig_absolute_path."/includes/domit/xml_domit_include.php");



// *** Get language files
if (file_exists($mosConfig_absolute_path."/components/com_medialibrary/language/{$mosConfig_lang}.php" ))
{

	include_once($mosConfig_absolute_path."/components/com_medialibrary/language/{$mosConfig_lang}.php" );
}
else
{

	include_once($mosConfig_absolute_path."/components/com_medialibrary/language/english.php" );
}


$bid = mosGetParam($_POST, 'bid', array (0));
$media_type = mosGetParam($_POST, 'media_type', "book" );
//$media_type = mosGetParam($_POST, 'media_type', "video" );

$section = mosGetParam( $_REQUEST, 'section', 'courses' );

if($medialibrary_configuration['debug'] == '1') {

	echo "Task: ".$task . "<br />";

	print_r($_POST);

	echo "<hr /><br />";

}

if (isset($section) && $section=='categories')
{
	switch ($task){

		case "edit" :
			editCategory($option, $bid[0]);
			break;

		case "new":
			editCategory($option, 0 );
			break;
		case "cancel":
			cancelCategory();
			break;
		case "save":
			saveCategory();
			break;
		case "remove":
			removeCategories($option, $bid);
			break;
		case "publish":
			publishCategories("com_medialibrary", $id, $bid, 1);
			break;
		case "unpublish":
			publishCategories("com_medialibrary", $id, $bid, 0);
			break;
		case "orderup":
			orderCategory($bid[0], -1);
			break;
		case "orderdown":
			orderCategory($bid[0], 1);
			break;
		case "accesspublic":
			accessCategory($bid[0], 0);
			break;
		case "accessregistered":
			accessCategory($bid[0], 1);
			break;
		case "accessspecial":
			accessCategory($bid[0], 2);
			break;
		case "show":
		default :
			showCategories();
	}
}
else
{

	switch ($task) {

		case "categories":
			echo "now work $section=='categories , this part not work"; exit;
			mosRedirect( "index2.php?option=categories&section=com_medialibrary" );
			break;

		case "new" :
			editMedia($option, 0,$media_type);
			break;

		case "edit" :
			editMedia($option, array_pop($bid),$media_type);
			break;

		case "refetchInfos" :
			refetchInfo($option, $bid);
			break;

		case "save" :
			saveMedia($option);
			break;

		case "remove" :
			removeMedia($bid, $option);
			break;

		case "publish" :
			publishMedias($bid, 1, $option);
			break;

		case "unpublish" :
			publishMedias($bid, 0, $option);
			break;

		case "cancel" :
			cancelEditMedia($option);
			break;

		case "bookorderdown" :
			orderBooks($bid[0], 1, $option);
			break;

		case "bookorderup" :
			orderBooks($bid[0], -1, $option);
			break;


		case "show_import_export" :
			importExport($option);
			break;

		case "import" :
			import($option);
			break;


		case "export" :
			export($option);
			break;

		case "config_frontend" :
			configure_frontend($option);
			break;

		case "config_backend" :
			configure_backend($option);
			break;

		case "config_save_frontend" :
			configure_save_frontend($option);
			break;

		case "config_save_backend" :
			configure_save_backend($option);
			break;

		case "lend" :
			if (mosGetParam($_POST, 'save') == 1) {
				saveLend($option, $bid);
			} else{
				lend($option, $bid);
			}
			break;



		case "lend_requests" :
			lend_requests($option, $bid);
			break;

		case "accept_lend_requests" :
			accept_lend_requests($option, $bid);
			break;

		case "decline_lend_requests" :
			decline_lend_requests($option, $bid);
			break;

		case "about" :
			HTML_medialibrary :: about();
			break;

		case "show_info" :
			showInfo($option, $bid);
			break;

		case "lend_return" :
			if (mosGetParam($_POST, 'save') == 1) {
				saveLend_return($option, $bid);
			} else {
				lend_return($option, $bid);
			}
			break;


			$medialibrary_configuration;
		case "delete_review" :
			$ids = explode(',',$bid[0]);
			delete_review($option, $ids[1]);
			editMedia($option, $ids[0],$media_type);
			break;

		case "edit_review" :
			$ids = explode(',',$bid[0]);
			edit_review($option, $ids[1], $ids[0]);
			break;

		case "update_review" :
			$title = mosGetParam($_POST, 'title') ;
			$comment = mosGetParam($_POST, 'comment') ;
			$rating = mosGetParam($_POST, 'rating') ;
			$book_id = mosGetParam($_POST, 'book_id') ;
			$review_id = mosGetParam($_POST, 'review_id') ;

			update_review($title,$comment,$rating,$review_id );
			editMedia($option, $book_id,$media_type );
			break;

		case "cancel_review_edit" :
			$book_id = mosGetParam($_POST, 'book_id') ;
			editMedia($option, $book_id, $media_type );
			break;

		default :
			showMedias($option);
			break;

	}

} //else

class CAT_Utils
{
	function categoryArray()
	{
		global $database;
		// get a list of the menu items
		$query = "SELECT c.*, c.parent_id AS parent"
		. "\n FROM #__categories c"
		. "\n WHERE section='com_medialibrary'"
		. "\n AND published <> -2"
		. "\n ORDER BY ordering" ;
		$database->setQuery($query);
		$items = $database->loadObjectList();
		// establish the hierarchy of the menu
		$children = array();
		// first pass - collect children
		foreach ($items as $v) {
			$pt = $v->parent;
			$list = @$children[$pt] ? $children[$pt] : array();
			array_push($list, $v);
			$children[$pt] = $list;
		}
		// second pass - get an indent list of the items
		$array = mosTreeRecurse(0, '', array(), $children);

		return $array;
	}

}



/**
* HTML Class
* Utility class for all HTML drawing classes
* @desc class General HTML creation class. We use it for back/front ends.
*/

class HTML
{
	// TODO :: merge categoryList and categoryParentList
	// add filter option ?
	function categoryList($id, $action, $options = array())
	{
		$list = CAT_Utils::categoryArray();
		// assemble menu items to the array
		foreach ($list as $item) {
			$options[] = mosHTML::makeOption($item->id, $item->treename);
		}
		$parent = mosHTML::selectList($options, 'catid', 'id="catid" class="inputbox" size="1" onchange="' . $action . '"', 'value', 'text', $id);
		return $parent;
	}

	function categoryParentList($id, $action,$is_new, $options = array())
	{
		global  $database;
		$list = CAT_Utils::categoryArray();
		$cat = new mosCategory($database);
		$cat->load($id);

		$this_treename = '';
		foreach ($list as $item) {
			if ($this_treename) {
				if ($item->id != $cat->id && strpos($item->treename, $this_treename) === false) {
					$options[] = mosHTML::makeOption($item->id, $item->treename);
				}
			} else {
				if ($item->id != $cat->id) {
					$options[] = mosHTML::makeOption($item->id, $item->treename);
				} else {
					$this_treename = "$item->treename/";
				}
			}
		}

    $parent= null;
    if($is_new){
      $parent = mosHTML::selectList($options, 'parent_id', 
        'class="inputbox" size="1"', 'value', 'text', $cat->parent_id);
    } else{
      $parent = mosHTML::selectList($options, 'parent_id', 
        'class="inputbox" size="1" disabled="true" ', 'value', 'text', $cat->parent_id);
    }

		return $parent;
	}






	function imageList($name, &$active, $javascript = null, $directory = null)
	{

		global $mosConfig_absolute_path;
		if (!$javascript)
		{
			$javascript = "onchange=\"javascript:if (document.adminForm." . $name . ".options[selectedIndex].value!='')    {document.imagelib.src='../images/stories/' + document.adminForm." . $name . ".options[selectedIndex].value} else {document.imagelib.src='../images/blank.png'}\"";
		}
		if (!$directory) {
			$directory = '/images/stories';
		}

		$imageFiles = mosReadDirectory($mosConfig_absolute_path.$directory);
		$images = array(mosHTML::makeOption('', _A_SELECT_IMAGE));
		foreach ($imageFiles as $file) {
			if (eregi("bmp|gif|jpg|png", $file)) {
				$images[] = mosHTML::makeOption($file);
			}
		}
		$images = mosHTML::selectList($images, $name, 'id="'.$name.'" class="inputbox" size="1" ' . $javascript, 'value', 'text',   $active);
		return $images;
	}
}






function MediaLibraryTreeRecurse( $id, $indent, $list, &$children, $maxlevel=9999, $level=0, $type=1 ) {

	if (@$children[$id] && $level <= $maxlevel) {
		$parent_id = $id;
		foreach ($children[$id] as $v) {
			$id = $v->id;

			if ( $type ) {
				$pre 	= '<sup>L</sup>&nbsp;';
				$spacer = '.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			} else {
				$pre 	= '- ';
				$spacer = '&nbsp;&nbsp;';
			}

			if ( $v->parent == 0 ) {
				$txt 	= $v->name;
			} else {
				$txt 	= $pre . $v->name;
			}
			$pt = $v->parent;
			$list[$id] = $v;
			$list[$id]->treename = "$indent$txt";
			$list[$id]->children = count( @$children[$id] );
			$list[$id]->all_fields_in_list = count(@$children[$parent_id]);

			$list = MediaLibraryTreeRecurse( $id, $indent . $spacer, $list, $children, $maxlevel, $level+1, $type );
		}
	}
	return $list;
}

function showCategories()
{

	global $database, $my, $option, $menutype, $mainframe, $mosConfig_list_limit;

	$section = "com_medialibrary";

	$sectionid = $mainframe->getUserStateFromRequest("sectionid{$section}{$section}", 'sectionid', 0);
	$limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
	$limitstart = $mainframe->getUserStateFromRequest("view{$section}limitstart", 'limitstart', 0);
	$levellimit = $mainframe->getUserStateFromRequest("view{$option}limit$menutype", 'levellimit', 10);

	$query = "SELECT  c.*, c.checked_out as checked_out_contact_category, c.parent_id as parent, g.name AS groupname, u.name AS editor"
	. "\n FROM #__categories AS c"
	. "\n LEFT JOIN #__users AS u ON u.id = c.checked_out"
	. "\n LEFT JOIN #__groups AS g ON g.id = c.access"
	. "\n WHERE c.section='$section'"
	. "\n AND c.published != -2"
	. "\n ORDER BY parent_id, ordering" ;

	$database->setQuery($query);

	$rows = $database->loadObjectList();

	foreach ($rows as $k => $v) {
		$rows[$k]->ncourses=0;
		$sql="SELECT COUNT(catid) AS cc FROM #__medialibrary WHERE catid=".$v->id;
		$database->setQuery($sql);
		$aa = $database->loadObjectList();
		$rows[$k]->nbook=($aa[0]->cc==0)?"-":"<a href=\"?option=com_medialibrary&section=book&catid=".$v->id."\">".($aa[0]->cc)."</a>";

	}


	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}
	// establish the hierarchy of the categories
	$children = array();
	// first pass - collect children
	foreach ($rows as $v) {
		$pt = $v->parent;
		$list = @$children[$pt] ? $children[$pt] : array();
		array_push($list, $v);
		$children[$pt] = $list;
	}
	// second pass - get an indent list of the items
	$list = MediaLibraryTreeRecurse(0, '', array(), $children, max(0, $levellimit-1));
	$total = count($list);

	require_once($GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php');
	$pageNav = new mosPageNav($total, $limitstart, $limit);

	$levellist = mosHTML::integerSelectList(1, 20, 1, 'levellimit', 'size="1" onchange="document.adminForm.submit();"', $levellimit);
	// slice out elements based on limits
	$list = array_slice($list, $pageNav->limitstart, $pageNav->limit);

	//echo "<pre>"; print_r($list); echo "</pre>";exit;

	$count = count($list);
	// number of Active Items
	/*  for ($i = 0; $i < $count; $i++) {
	$query = "SELECT COUNT( d.id )"
	. "\n FROM #__categories AS d"
	. "\n WHERE d.catid = " . $list[$i]->id;
	// . "\n AND d.state <> '-2'";
	$database->setQuery($query);
	$active = $database->loadResult();
	$list[$i]->documents = $active;
	}*/
	// get list of sections for dropdown filter
	$javascript = 'onchange="document.adminForm.submit();"';
	$lists['sectionid'] = mosAdminMenus::SelectSection('sectionid', $sectionid, $javascript);

	HTML_Categories::show($list, $my->id, $pageNav, $lists, 'other');
}





function editCategory($section = '', $uid = 0)
{

	global $database, $my;
	global $mosConfig_absolute_path, $mosConfig_live_site;


	$type = mosGetParam($_REQUEST, 'type', '');
	$redirect = mosGetParam($_POST, 'section', '');;
	$row = new mosCategory($database);
	// load the row from the db table
	$row->load($uid);
	// fail if checked out not by 'me'
	if ($row->checked_out && $row->checked_out <> $my->id) {
		mosRedirect('index2.php?option=com_medialibrary&task=categories', 'The category ' . $row->title . ' is currently being edited by another administrator');
	}

  $is_new = false;
	if ($uid) {
		// existing record
		$row->checkout($my->id);
		// code for Link Menu
	} else {
		// new record
    $is_new = true;
		$row->section = $section;
		$row->published = 1;
	}
	// make order list
	$order = array();

	$database->setQuery("SELECT COUNT(*) FROM #__categories WHERE section='$row->section'");
	$max = intval($database->loadResult()) + 1;

	for ($i = 1; $i < $max; $i++) {
		$order[] = mosHTML::makeOption($i);
	}
	// build the html select list for ordering
	$query = "SELECT ordering AS value, title AS text"
	. "\n FROM #__categories"
	. "\n WHERE section = '$row->section'"
	. "\n ORDER BY ordering" ;

	$lists['ordering'] = mosAdminMenus::SpecificOrdering($row, $uid, $query);
	// build the select list for the image positions
	$active = ($row->image_position ? $row->image_position : 'left');
	$lists['image_position'] = mosAdminMenus::Positions('image_position', $active, null, 0, 0);
	// Imagelist
	$lists['image'] = HTML::imageList('image', $row->image);
	// build the html select list for the group access
	$lists['access'] = mosAdminMenus::Access($row);
	// build the html radio buttons for published
	$lists['published'] = mosHTML::yesnoRadioList('published', 'class="inputbox"', $row->published);
	// build the html select list for paraent item
	$options = array();
	$options[] = mosHTML::makeOption('0', _A_SELECT_TOP);


	$lists['parent'] = HTML::categoryParentList($row->id, "",$is_new, $options);

	HTML_Categories::edit($row, $section, $lists, $redirect);
}








function saveCategory()
{
	global $database;
	$row = new mosCategory($database);
	if (!$row->bind($_POST)) {
		echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
		exit();
	}
	$row->section='com_medialibrary';
	$row->parent_id=$_REQUEST['parent_id'];

	if (!$row->check()) {
		echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
		exit();
	}

	$row->checkin();
	$row->updateOrder("section='com_medialibrary' AND parent_id='$row->parent_id'");

	if ($oldtitle = mosGetParam($_POST, 'oldtitle', null)) {
		if ($oldtitle != $row->title) {
			$database->setQuery("UPDATE #__categories " . "\n SET name='$row->title' " . "\n WHERE name='$oldtitle' " . "\n    AND section='com_medialibrary'");

			$database->query();
		}
	}
	mosRedirect('index2.php?option=com_medialibrary&section=categories');
}

//this function check - is exist books in this folder and folders under this category
function is_exist_curr_and_subcategory_books($catid) {
	global $database, $my;

	$query = "SELECT *, COUNT(a.id) AS numlinks FROM #__categories AS cc"
	. "\n LEFT JOIN #__medialibrary AS a ON a.catid = cc.id"
	. "\n WHERE a.published='1' AND a.approved='1' AND section='com_medialibrary' AND cc.id='$catid' AND cc.published='1' AND cc.access <= '$my->gid'"
	. "\n GROUP BY cc.id"
	. "\n ORDER BY cc.ordering";
	$database->setQuery( $query );
	$categories = $database->loadObjectList();
	if( count($categories) != 0 ) return true;

	$query = "SELECT id "
	. "FROM #__categories AS cc "
	. " WHERE section='com_medialibrary' AND parent_id='$catid' AND published='1' AND access<='$my->gid'";
	$database->setQuery( $query );
	$categories = $database->loadObjectList();

	if( count($categories) == 0 ) return false;

	foreach($categories as $k) {
		if( is_exist_curr_and_subcategory_books($k->id) ) return true;
	}
	return false;
}//end function

function removeCategoriesFromDB($cid){
	global $database, $my;

	$query = "SELECT id,  "
	. "FROM #__categories AS cc "
	. " WHERE section='com_medialibrary' AND parent_id='$cid' AND published='1' AND access<='$my->gid'";
	$database->setQuery( $query );
	$categories = $database->loadObjectList();
  if ($database->getErrorNum()) {
    echo $database->stderr();
  }

	//    echo $database->getErrorMsg() ;

	if( count($categories) != 0 ) {
		//delete child
		foreach($categories as $k) {
			removeCategoriesFromDB($k->id) ;
		}
	}

	$sql="DELETE FROM #__categories WHERE id = $cid ";
	$database->setQuery($sql);
	$database->query();

}


/**
* Deletes one or more categories from the categories table
* 
* @param string $ The name of the category section
* @param array $ An array of unique category id numbers
*/
function removeCategories($section, $cid)

{
	global $database;

	if (count($cid) < 1) {
		echo "<script> alert('Select a category to delete'); window.history.go(-1);</script>\n";
		exit;
	}

	foreach ($cid as $catid) {
		if(is_exist_curr_and_subcategory_books( $catid  ) ){
			echo "<script> alert('Some category from yours select contain books. \\n Please remove books first!'); window.history.go(-1); </script>\n";
			exit ;
		}
	}

	foreach ($cid as $catid) {
		removeCategoriesFromDB($catid) ;
	}

	/*    $cids = implode(',', $cid);

	$query = "SELECT c.id AS numcat, c.name, COUNT(s.catid ) AS numkids"
	. "\n FROM #__categories AS c"
	. "\n LEFT JOIN #__medialibrary AS s ON s.catid=c.id"
	. "\n WHERE c.id IN ($cids)"
	. "\n GROUP BY c.id" ;

	// add set query
	$database->setQuery($query);
	if (!($rows = $database->loadObjectList())) {
	echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
	return ;
	}

	$err = array();
	$new_cid = array();

	foreach ($rows as $row) {

	if ($row->numkids == 0) {
	$new_cid[] = $row->numcat;
	} else {
	$err[] = $row->name;
	}
	}

	if (count($new_cid)) {
	$new_cids = implode(',', $new_cid);

	if (count($cid)) {
	$new_cids = implode(',', $cid);

	$sql="DELETE FROM #__categories WHERE id IN ($new_cids)";
	$database->setQuery($sql);

	if (!$database->query()) {
	echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
	return ;
	}
	}

	if (count($err)) {
	if (count($err) > 1) {
	$new_cids = implode(', ', $err);
	$msg = "Categories : $new_cids -";
	} else {
	$msg = "Category " . $err[0] ;
	}
	$msg .= ' cannot be removed. There are associated records and/or subcategories';
	mosRedirect('index2.php?option=com_medialibrary&section=categories&mosmsg=' . $msg);
	}
	*/
	$msg = (count($err) > 1 ? "Categories " : _CATEGORIES_NAME . " ") . _DELETED;
	mosRedirect('index2.php?option=com_medialibrary&section=categories&mosmsg=' . $msg) ;
}




/**
* Publishes or Unpublishes one or more categories
* 
* @param string $ The name of the category section
* @param integer $ A unique category id (passed from an edit form)
* @param array $ An array of unique category id numbers
* @param integer $ 0 if unpublishing, 1 if publishing
* @param string $ The name of the current user
*/

function publishCategories($section, $categoryid = null, $cid = null, $publish = 1)
{
	global $database, $my;

	if (!is_array($cid)) {
		$cid = array();
	}
	if ($categoryid) {
		$cid[] = $categoryid;
	}

	if (count($cid) < 1) {
		$action = $publish ? _PUBLISH : _DML_UNPUBLISH;
		echo "<script> alert('" . _DML_SELECTCATTO . " $action'); window.history.go(-1);</script>\n";
		exit;
	}

	$cids = implode(',', $cid);

	$query = "UPDATE #__categories SET published='$publish'"
	. "\nWHERE id IN ($cids) AND (checked_out=0 OR (checked_out='$my->id'))" ;
	$database->setQuery($query);
	if (!$database->query()) {
		echo "<script> alert('" . $database->stderr() . "'); window.history.go(-1); </script>\n";
		exit();
	}

	if (count($cid) == 1) {
		$row = new mosCategory($database);
		$row->checkin($cid[0]);
	}

	mosRedirect('index2.php?option=com_medialibrary&section=categories');
}

/**
* Cancels an edit operation
* 
* @param string $ The name of the category section
* @param integer $ A unique category id
*/
function cancelCategory()
{
	global $database;

	$row = new mosCategory($database);
	$row->bind($_POST);
	$row->checkin();
	mosRedirect('index2.php?option=com_medialibrary&section=categories');
}

/**
* Moves the order of a record
* 
* @param integer $ The increment to reorder by
*/




function orderCategory($uid, $inc)
{
	global $database;
	$row = new mosCategory($database);
	$row->load($uid);
	if($row->ordering == 1 && $inc == -1) mosRedirect('index2.php?option=com_medialibrary&section=categories');

	$new_order = $row->ordering + $inc ;

	//change ordering - for other element
	$query = "UPDATE #__categories SET ordering='".($row->ordering)."'"
	. "\nWHERE parent_id = $row->parent_id and ordering=$new_order" ;
	$database->setQuery($query);
	$database->query();

	//change ordering - for this element
	$query = "UPDATE #__categories SET ordering='".$new_order."'"
	. "\nWHERE id = $uid" ;
	$database->setQuery($query);
	$database->query();

	mosRedirect('index2.php?option=com_medialibrary&section=categories');

	/*    $row = new mosCategory($database);
	$row->load($uid);
	$row->move($inc, "section='$row->section'");
	mosRedirect('index2.php?option=com_medialibrary&section=categories');
	*/
}

/**
* changes the access level of a record
* 
* @param integer $ The increment to reorder by
*/
function accessCategory($uid, $access)
{
	global $database;

	$row = new mosCategory($database);
	$row->load($uid);
	$row->access = $access;

	if (!$row->check()) {
		return $row->getError();
	}
	if (!$row->store()) {
		return $row->getError();
	}

	mosRedirect('index2.php?option=com_medialibrary&section=categories');
}


function update_review($title,$comment,$rating,$review_id ) {
	global $database;

	//update review where id =.. ;
	$database->setQuery('update #__medialibrary_review set rating='.$rating.
	', title="'.$title.'", comment="'.$comment.'" where id = '.$review_id.' ;' );

	$database->query();
  if ($database->getErrorNum()) {
    echo $database->stderr();
  }

}


function edit_review($option, $review_id,$book_id) {
	global $database;


	$database->setQuery("SELECT * FROM #__medialibrary_review WHERE id=".$review_id." ");

	$review = $database->loadObjectList();

  if ($database->getErrorNum()) {
    echo $database->stderr();
  }


	HTML_medialibrary :: edit_review($option, $book_id, $review);

}

/*
* Add Nikolay.
* Function for delete coment
* (comment for every book)
* in database.
*/

function delete_review($option, $id) {
	global $database;

	//delete review where id =.. ;
	$database->setQuery("DELETE FROM #__medialibrary_review WHERE #__medialibrary_review.id=".$id.";");

	$database->query();

  if ($database->getErrorNum()) {
    echo $database->stderr();
  }
}



function showInfo($option, $bid){

	if(is_array($bid) && count($bid) > 0){
		$bid = $bid[0];
	}
	echo "Test: " . $bid;
}

function decline_lend_requests($option, $bids){

	global $database;

	foreach($bids as $bid){
		$lend_request = new mosMediaLibrary_lend_request($database);
		$lend_request->load($bid);
		$tmp = $lend_request->decline();
		if($tmp != null){
			echo "<script> alert('" .$tmp . "'); window.history.go(-1); </script>\n";
			exit ();
		}
	}

	mosRedirect("index2.php?option=$option&task=lend_requests");
}

function accept_lend_requests($option, $bids){
	global $database;

	foreach($bids as $bid){
		$lend_request = new mosMediaLibrary_lend_request($database);
		$lend_request->load($bid);
		$tmp = $lend_request->accept();
		if($tmp != null){
			echo "<script> alert('" .$tmp . "'); window.history.go(-1); </script>\n";
			exit ();
		}
	}
	mosRedirect("index2.php?option=$option&task=lend_requests");
}



function lend_requests($option, $bid){

	global $database, $mainframe, $mosConfig_list_limit;

	$limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
	$limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);

	$database->setQuery("SELECT count(*) FROM #__medialibrary AS a".
	" LEFT JOIN #__medialibrary_lend_request AS l".
	" ON l.fk_mediaid = a.id".
	" WHERE l.status = 0");
	$total = $database->loadResult();

  if ($database->getErrorNum()) {
    echo $database->stderr();
  }

	require_once ($GLOBALS['mosConfig_absolute_path'].'/administrator/includes/pageNavigation.php');
	$pageNav = new mosPageNav($total, $limitstart, $limit);

	
  $selectstring = "SELECT l.id, library.media_type, library.media_id," .
    "cc.title AS category, library.catid, ".
    " l.id as lendid, l.lend_from as lend_from, " .
    " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
    " l.lend_until as lend_until, l.user_name as user_name ," .
    " l.user_email as user_email, l.user_mailing as user_mailing ," .
    " other_table.id as media_type_id,  other_table.title as title  " .
    " FROM #__medialibrary_lend_request AS l, #__medialibrary AS library " .
    " LEFT JOIN #__categories AS cc ON cc.id = library.catid "  .
    " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game ".
    " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
    " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
    " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
    " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
    "  WHERE l.status = 0 and l.fk_mediaid = library.id " .
    " ORDER BY l.lend_from, l.lend_until, l.user_name ".
    " LIMIT $pageNav->limitstart,$pageNav->limit;";
$database->setQuery( $selectstring );

	$lend_requests = $database->loadObjectList();

  if ($database->getErrorNum()) {
    echo $database->stderr();
  }

	//	print_r($total);

	HTML_medialibrary :: showRequestLendMedias($option, $lend_requests, $pageNav);
}


/**
* Compiles a list of records
* @param database - A database connector object
* select categories
*/
function showMedias($option)
{
	global $database, $mainframe, $mosConfig_list_limit;

	$limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
	$limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
	$catid = $mainframe->getUserStateFromRequest("catid{$option}", 'catid', '-1');//old 0
	$lend = $mainframe->getUserStateFromRequest("lend{$option}", 'lend', '-1');
  $pub = $mainframe->getUserStateFromRequest("pub{$option}", 'pub', '-1');
  $type = $mainframe->getUserStateFromRequest("type{$option}", 'type', '-1');

	$search = $mainframe->getUserStateFromRequest("search{$option}", 'search', '');
	$search = $database->getEscaped(trim(strtolower($search)));

	$where = array ();
	//anton code show media library
	//$database->setQuery("SELECT count(*) FROM #__videolibrary WHERE ");
	if ($lend == "lend") {
		array_push($where, "library.fk_lendid <> 0");
	} else if ($lend == "not_lend") {
		array_push($where, "library.fk_lendid = 0");
	}
  if ($pub== "pub") {
    array_push($where, "library.published = 1");
  } else if ($pub == "not_pub") {
    array_push($where, "library.published = 0");
  }
  if ($type== "-1" || $type == "0 ") {
    ; 
  } else  {
    array_push($where, "library.media_type = '$type' ");
  }
	if ($catid > 0) {
		array_push($where, "library.catid='$catid'");
	}
	if ($search) {
		array_push($where, "(LOWER(other_table.title) LIKE '%$search%' OR LOWER(other_table.comment) LIKE '%$search%' ".
    " OR LOWER(other_table.ext1) LIKE '%$search%' OR LOWER(other_table.ext2) LIKE '%$search%' ".
    " OR LOWER(other_table.ext3) LIKE '%$search%' )");
	}

  $selectstring = "SELECT  count(*) " .
    " FROM #__medialibrary AS library " .
    " LEFT JOIN #__categories AS cc ON cc.id = library.catid "  .
    " LEFT JOIN #__medialibrary_lend AS l ON library.fk_lendid = l.id " .
    " LEFT JOIN #__users AS u ON u.id = library.checked_out " .
    " LEFT JOIN (SELECT id, title, 'game' as type, comment, studio as ext1, binding as ext2, platform as ext3 FROM #__medialibrary_game ".
    " UNION all SELECT id, title, 'music' as type, comment,artist as ext1, label as ext2, tracklist as ext3 FROM #__medialibrary_music " .
    " UNION all SELECT id, title, 'book' as type,comment,authors as ext1, manufacturer as ext2, edition as ext3 FROM #__medialibrary_book " .
    " UNION all SELECT id, title, 'video' as type, comment,actors as ext1, producers as ext2, format as ext3 FROM #__medialibrary_video) " .
    " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
    (count($where) ? "  WHERE ".implode(' AND ', $where) : "") ;

	$database->setQuery($selectstring);
	$total = $database->loadResult();

  if ($database->getErrorNum()) {
    echo $database->stderr();
  }


	require_once ($GLOBALS['mosConfig_absolute_path'].'/administrator/includes/pageNavigation.php');
	$pageNav = new mosPageNav($total, $limitstart, $limit);

	$selectstring = "SELECT library.id, library.media_type, library.media_id," .
	  "cc.title AS category, library.published, library.hits, library.checked_out, library.catid, ".
	  " library.informationFrom, l.id as lendid, l.lend_from as lend_from, " .
	  " l.lend_return as lend_return, " .
	  " l.lend_until as lend_until ," .
	  " u.name AS editor, " .
	  " other_table.id as media_type_id,  other_table.title as title  " .
	  " FROM #__medialibrary AS library " .
	  " LEFT JOIN #__categories AS cc ON cc.id = library.catid "  .
	  " LEFT JOIN #__medialibrary_lend AS l ON library.fk_lendid = l.id " .
	  " LEFT JOIN #__users AS u ON u.id = library.checked_out " .
    " LEFT JOIN (SELECT id, title, 'game' as type, comment, studio as ext1, binding as ext2, platform as ext3 FROM #__medialibrary_game ".
    " UNION all SELECT id, title, 'music' as type, comment,artist as ext1, label as ext2, tracklist as ext3 FROM #__medialibrary_music " .
    " UNION all SELECT id, title, 'book' as type,comment,authors as ext1, manufacturer as ext2, edition as ext3 FROM #__medialibrary_book " .
    " UNION all SELECT id, title, 'video' as type, comment,actors as ext1, producers as ext2, format as ext3 FROM #__medialibrary_video) " .
	  " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
	  (count($where) ? "  WHERE ".implode(' AND ', $where) : "") .
	  " ORDER BY library.catid, library.ordering " .
	  " LIMIT $pageNav->limitstart,$pageNav->limit;";

	$database->setQuery($selectstring);
	$rows = $database->loadObjectList();
//print_r($rows); exit;
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}
#print_r($rows); exit;

	// get list of categories
	$categories[] = mosHTML :: makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
	$categories[] = mosHTML :: makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_CATEGORIES);

	//*************   begin add for sub category in select in manager books   *************
	$options = $categories;
	$id = 0;//$categories_array;
	$list = CAT_Utils::categoryArray();

	$cat = new mosCategory($database);
	$cat->load($id);

	$this_treename = '';
	foreach ($list as $item) {
		if ($this_treename) {
			if ($item->id != $cat->id && strpos($item->treename, $this_treename) === false) {
				$options[] = mosHTML::makeOption($item->id, $item->treename);
			}
		} else {
			if ($item->id != $cat->id) {
				$options[] = mosHTML::makeOption($item->id, $item->treename);
			} else {
				$this_treename = "$item->treename/";
			}
		}
	}

	$clist = mosHTML::selectList($options, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid);//new nik edit

	//	$clist = mosHTML :: selectList($categories, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid);//old valid
	//*****  end add for sub category in select in manager books   **********

	$lendmenu[] = mosHTML :: makeOption('0', _MEDIALIBRARY_LABEL_SELECT_TO_LEND);
	$lendmenu[] = mosHTML :: makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_LEND);
	$lendmenu[] = mosHTML :: makeOption('not_lend', _MEDIALIBRARY_LABEL_SELECT_NOT_LEND);
	$lendmenu[] = mosHTML :: makeOption('lend', _MEDIALIBRARY_LABEL_SELECT_LEND);

	$lendlist = mosHTML :: selectList($lendmenu, 'lend', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $lend);

  $pubmenu[] = mosHTML :: makeOption('0', _MEDIALIBRARY_LABEL_SELECT_TO_PUBLIC);
  $pubmenu[] = mosHTML :: makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_PUBLIC);
  $pubmenu[] = mosHTML :: makeOption('not_pub', _MEDIALIBRARY_LABEL_SELECT_NOT_PUBLIC);
  $pubmenu[] = mosHTML :: makeOption('pub', _MEDIALIBRARY_LABEL_SELECT_PUBLIC);

  $publist = mosHTML :: selectList($pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);

  $typemenu[] = mosHTML :: makeOption('0', _MEDIALIBRARY_LABEL_SELECT_TYPE);
  $typemenu[] = mosHTML :: makeOption('-1', _MEDIALIBRARY_LABEL_SELECT_ALL_TYPE);
  $typemenu[] = mosHTML :: makeOption('game', "game");
  $typemenu[] = mosHTML :: makeOption('music', "music");
  $typemenu[] = mosHTML :: makeOption('book', "book");
  $typemenu[] = mosHTML :: makeOption('video', "video");

  $typelist = mosHTML :: selectList($typemenu, 'type', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $type);


	HTML_medialibrary :: showMedias($option, $rows, $clist, $lendlist, $publist,$typelist, $search, $pageNav);
}


/**
* Compiles information to add or edit medias type
* @param integer bid The unique id of the record to edit (0 if new)
* @param array option the current options
*/
function editMedia($option,$bid,$media_type)
{
	global $database, $my;
	$medialibrary = new mosMedialibrary($database);
	//определяем основную таблицу
	$medialibrary->load(intval($bid));
	//определяем таблицу для типа
  //echo "111111111111:".$medialibrary->id .":".$bid.":".$medialibrary->media_type; exit;
  //debug!!!!!!!!!!!
  if( $bid === 0 )  {
    $medialibrary->media_id = 0 ;
    $medialibrary->media_type = $media_type;
  }


	switch ($medialibrary->media_type)
	{
		case 'book':
			$media_class = new mosMedialibrary_book($database);
			$media_class->load($medialibrary->media_id);
			editing_book($media_class, $medialibrary, $option, $bid);
			break;
		case 'video':
			$media_class = new mosMedialibrary_video($database);
			$media_class->load($medialibrary->media_id);
			editing_video($media_class, $medialibrary, $option, $bid);
			break;
		case 'music':
			$media_class = new mosMedialibrary_music($database);
			$media_class->load($medialibrary->media_id);
			editing_music($media_class, $medialibrary, $option, $bid);
			break;
		case 'game':
			$media_class = new mosMedialibrary_game($database);
			$media_class->load($medialibrary->media_id);
			editing_game($media_class, $medialibrary, $option, $bid);
			break;
	}

}



/**
* Saves the record on an edit form submit
* @param database A database connector object
*/

function saveMedia($option)
{
	global $database, $my,$mosConfig_absolute_path, $mosConfig_live_site, $medialibrary_configuration;

  $media = new mosMediaLibrary($database);
//print_r("saveMedia"); exit;

  if (!$media->bind($_POST)) {
    echo "<script> alert('".$media->getError()."'); window.history.go(-1); </script>\n";
    exit ();
  }
// print_r($_POST); 
// echo "----------------------";
// print_r($media); exit;

  $media_type_class = '';
  switch ($media->media_type)
  {
    case 'book':

      $media_type_class = new mosMedialibrary_book($database);

      if (!$media_type_class->bind($_POST)) {
        echo "<script> alert('".$media_type_class->getError()."'); window.history.go(-1); </script>\n";
        exit ();
      }
        $media_type_class->id = $_POST['media_id'];
        $media_type_class->book_id = $_POST['media_type_id'];
      	$media_type_class->isbn = $_POST['asin_isbn'];

      //fetch all information from the webservices if necessary
      if(intval($media->informationFrom) != 0 ){
        //Amazon WS
        $media_type_class = mosMedialibraryWS :: fetchAmazonInfosForBook($media, $media_type_class);
      }


      //check error
      if (is_string($media_type_class)) {
    
        //there was an error while fetching!
        echo "<script> alert('" . $media_type_class . "'); window.history.go(-1); </script>\n";
        exit ();
      }

      if($_POST['ebook_Url'] != '') $media_class->ebookURL = $_POST['ebook_Url'];

      //delete old ebook file if neccesary
      $delete_edocument = mosGetParam($_POST, 'delete_edocument', 0);
      if($delete_edocument != '0'){
        @unlink($mosConfig_absolute_path . $delete_edocument);
        $media_type_class->ebookURL = "";
      }

      //storing e-Document
      $file = $_FILES['edocument_file'];

      //check if fileupload is correct
      if($medialibrary_configuration['emedias']['allow'] && intval($file['error']) > 0 
          && intval($file['error']) < 4){
        echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR .
         "'); window.history.go(-1); </script>\n";
        exit ();
    
      }else if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) != 4){

        $file_new = $mosConfig_absolute_path . $medialibrary_configuration['emedias']['location'] .
          $file['name'];
//        echo $file_new;
        if(!move_uploaded_file($file['tmp_name'],  $file_new)){
    
          echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR . 
            "'); window.history.go(-1); </script>\n";
          exit ();
        }else {
    
          $media_type_class->ebookURL = $mosConfig_live_site . 
            $medialibrary_configuration['emedias']['location'] . $file['name'];
    
        }
      }
      $file = $_FILES['picture_file'];

      //check if fileupload is correct
      if($file['size'] != 0 && ( $file['error'] != 0
          || strpos($file['type'],'image') === false
          ||strpos($file['type'],'image')===""))
      {
    
        echo "<script> alert('" . _MEDIALIBRARY_LABEL_PICTURE_URL_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
        exit ();
    
      }
    
      //store pictures locally if neccesary, first check remote URL
      $retVal = null;
      if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1
          && trim($media_type_class->imageURL) != "" 
          && $file['size'] == 0 ){

        $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, null);

      }
      if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && $file['size'] != 0)
      {
        $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, $file);
        if ($retVal != null)
        {
          echo "<script> alert('".$retVal."'); window.history.go(-1); </script>\n";
          exit ();
        }
      }

      if($file['size'] == 0){
        $file = null;
      }

      //save_book($media_class, $medialibrary, $option, $bid);
      break;
    case 'video':
      $media_type_class = new mosMedialibrary_video($database);

      if (!$media_type_class->bind($_POST)) {
        echo "<script> alert('".$media_type_class->getError()."'); window.history.go(-1); </script>\n";
        exit ();
      }
      $media_type_class->id = $_POST['media_id'];
      $media_type_class->video_id = $_POST['media_type_id'];
      $media_type_class->asin = $_POST['asin_isbn'];
      $media_type_class->format = $_POST['video_format'];

	    //fetch all information from the webservices if necessary
	    if(intval($media->informationFrom) != 0 ){
		    //Amazon WS
		    $media_type_class = mosMedialibraryWS :: fetchAmazonInfosForVideo($media, $media_type_class);
	    }

      //check error
      if (is_string($media_type_class)) {
        //there was an error while fetching!
        echo "<script> alert('" . $media_type_class . "'); window.history.go(-1); </script>\n";
        exit ();
      }

      if($_POST['evideo_Url'] != '') $media_class->evideoURL = $_POST['evideo_Url'];
      //delete old emusik file if neccesary
      $delete_edocument = mosGetParam($_POST, 'delete_edocument', 0);
      if($delete_edocument != '0'){
        @unlink($mosConfig_absolute_path . $delete_edocument);
        $media_type_class->evideoURL = "";
      }

      //storing e-Document
      $file = $_FILES['edocument_file'];

      //check if fileupload is correct
      if($medialibrary_configuration['emedias']['allow'] && intval($file['error']) > 0 && intval($file['error']) < 4){
        echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
        exit ();
    
      }else if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) != 4){

        $file_new = $mosConfig_absolute_path . $medialibrary_configuration['emedias']['location'] . $file['name'];
//        echo $file_new;
        if(!move_uploaded_file($file['tmp_name'],  $file_new)){
    
          echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
          exit ();
        }else {
    
          $media_type_class->evideoURL = $mosConfig_live_site . 
            $medialibrary_configuration['emedias']['location'] . $file['name'];

        }
      }

    	$file = $_FILES['picture_file'];

      //check if fileupload is correct
      if($file['size'] != 0 && ( $file['error'] != 0
          || strpos($file['type'],'image') === false
          ||strpos($file['type'],'image')===""))
      {
    
        echo "<script> alert('" . _MEDIALIBRARY_LABEL_PICTURE_URL_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
        exit ();
    
      }

      //store pictures locally if neccesary, first check remote URL
      $retVal = null;
      if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1
          && trim($media_type_class->imageURL) != "" 
          && $file['size'] == 0 ){

        $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, null);

      }
      if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && $file['size'] != 0)
      {
        $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, $file);
        if ($retVal != null)
        {
          echo "<script> alert('".$retVal."'); window.history.go(-1); </script>\n";
          exit ();
        }
      }
    
      if($file['size'] == 0){
        $file = null;
      }

      //save_video($media_class, $medialibrary, $option, $bid);
      break;

    case 'music':
//  music 
 	    $media_type_class = new mosMedialibrary_music($database);
 
      if (!$media_type_class->bind($_POST)) {
	       echo "<script> alert('".$media_type_class->getError()."'); window.history.go(-1); </script>\n";
        exit ();
      }
        $media_type_class->id = $_POST['media_id'];
      	$media_type_class->music_id = $_POST['media_type_id'];
      	$media_type_class->asin = $_POST['asin_isbn'];

      //fetch all information from the webservices if necessary
     if(intval($media->informationFrom) != 0 ){
        //Amazon WS
        $media_type_class = mosMedialibraryWS :: fetchAmazonInfosForMusic($media, $media_type_class);
      }

      //check error
      if (is_string($media_type_class)) {
           //there was an error while fetching!
        echo "<script> alert('" . $media_type_class . "'); window.history.go(-1); </script>\n";
        exit ();
      }

      if($_POST['emusic_Url'] != '') $media_class->emusicURL = $_POST['emusic_Url'];
      //delete old emusik file if neccesary
      $delete_edocument = mosGetParam($_POST, 'delete_edocument', 0);
      if($delete_edocument != '0'){
        @unlink($mosConfig_absolute_path . $delete_edocument);
        $media_type_class->emusicURL = "";
      }

      //storing e-Document
      $file = $_FILES['edocument_file'];

      //check if fileupload is correct
      if($medialibrary_configuration['emedias']['allow'] && intval($file['error']) > 0 && intval($file['error']) < 4){
        echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
        exit ();
    
      }else if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) != 4){

        $file_new = $mosConfig_absolute_path . $medialibrary_configuration['emedias']['location'] . $file['name'];
//        echo $file_new;
        if(!move_uploaded_file($file['tmp_name'],  $file_new)){
    
          echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
          exit ();
        }else {
    
          $media_type_class->emusicURL = $mosConfig_live_site . 
            $medialibrary_configuration['emedias']['location'] . $file['name'];

        }
      }

    	$file = $_FILES['picture_file'];

      //check if fileupload is correct
      if($file['size'] != 0 && ( $file['error'] != 0
          || strpos($file['type'],'image') === false
          ||strpos($file['type'],'image')===""))
      {
    
        echo "<script> alert('" . _MEDIALIBRARY_LABEL_PICTURE_URL_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
        exit ();
    
      }

      //store pictures locally if neccesary, first check remote URL
      $retVal = null;
      if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1
          && trim($media_type_class->imageURL) != "" 
          && $file['size'] == 0 ){

        $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, null);

      }
      if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && $file['size'] != 0)
      {
        $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, $file);
        if ($retVal != null)
        {
          echo "<script> alert('".$retVal."'); window.history.go(-1); </script>\n";
          exit ();
        }
      }
    
      if($file['size'] == 0){
        $file = null;
      }
	    break;

    case 'game':
      $media_type_class = new mosMedialibrary_game($database);
	
	if (!$media_type_class->bind($_POST)) {
	       echo "<script> alert('".$media_type_class->getError()."'); window.history.go(-1); </script>\n";
        exit ();
      }
	
        $media_type_class->id = $_POST['media_id'];
      	$media_type_class->game_id = $_POST['media_type_id'];
      	$media_type_class->asin = $_POST['asin_isbn'];


      //fetch all information from the webservices if necessary
     if(intval($media->informationFrom) != 0 ){
        //Amazon WS
        $media_type_class = mosMedialibraryWS :: fetchAmazonInfosForGame($media, $media_type_class);
      }
	
      //check error
      if (is_string($media_type_class)) {
           //there was an error while fetching!
        echo "<script> alert('" . $media_type_class . "'); window.history.go(-1); </script>\n";
        exit ();
      }

     if($_POST['egame_Url'] != '') $media_class->emusicURL = $_POST['egame_Url'];
      //delete old emusik file if neccesary
      $delete_edocument = mosGetParam($_POST, 'delete_edocument', 0);
      if($delete_edocument != '0'){
        @unlink($mosConfig_absolute_path . $delete_edocument);
        $media_type_class->egameURL = "";
      }

      //storing e-Document
      $file = $_FILES['edocument_file'];

      //check if fileupload is correct
      if($medialibrary_configuration['emedias']['allow'] && intval($file['error']) > 0 && intval($file['error']) < 4){
        echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
        exit ();
    
      }else if ($medialibrary_configuration['emedias']['allow'] && intval($file['error']) != 4){

        $file_new = $mosConfig_absolute_path . $medialibrary_configuration['emedias']['location'] . $file['name'];
//        echo $file_new;
        if(!move_uploaded_file($file['tmp_name'],  $file_new)){
    
          echo "<script> alert('" . _MEDIALIBRARY_LABEL_EDOCUMENT_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
          exit ();
        }else {
    
          $media_type_class->egameURL = $mosConfig_live_site . 
            $medialibrary_configuration['emedias']['location'] . $file['name'];

        }
      }
	
    	$file = $_FILES['picture_file'];

      //check if fileupload is correct
      if($file['size'] != 0 && ( $file['error'] != 0
          || strpos($file['type'],'image') === false
          ||strpos($file['type'],'image')===""))
      {
          echo "<script> alert('" . _MEDIALIBRARY_LABEL_PICTURE_URL_UPLOAD_ERROR . "'); window.history.go(-1); </script>\n";
        exit ();
    
      }

      //store pictures locally if neccesary, first check remote URL
      $retVal = null;
      if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1
          && trim($media_type_class->imageURL) != "" 
          && $file['size'] == 0 ){

        $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, null);

      }
      if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1 && $file['size'] != 0)
      {
        $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, $file);
        if ($retVal != null)
        {

          echo "<script> alert('".$retVal."'); window.history.go(-1); </script>\n";
          exit ();
        }
      }

      if($file['size'] == 0){
        $file = null;
      }

     // $media_type_class->load($medialibrary->media_id);
      //editing_game($media_type_class, $medialibrary, $option, $bid);
      break;
  }
	//end of switch

//print_r($media_type_class);exit;
 //$database->debug(7);
  $media->date = date("Y-m-d H:i:s");

  //remove escaped slashes
  if(get_magic_quotes_gpc()) {
    $media_type_class->comment = stripslashes($media_type_class->comment);  
  }


	if (!$media_type_class->check() ) {
	  echo "<script> alert('".$media_type_class->getError()."'); window.history.go(-1); </script>\n";
	  exit ();
	}
		
	if (!$media->check()) {
	  echo "<script> alert('".$media->getError()."'); window.history.go(-1); </script>\n";
	  exit ();
	}

	if (!$media_type_class->store()) {
	  echo "<script> alert('".$media_type_class->getError()."'); window.history.go(-1); </script>\n";
	  exit ();
	}

	$media->media_id = $media_type_class->id;

	if (!$media->store()) {
    $media_type_class->delete( $media_type_class->id );
	  echo "<script> alert('".$media->getError()."'); window.history.go(-1); </script>\n";
	  exit ();
	}

  $media->checkin();
  $media->updateOrder( "catid='$media->catid'" );

  //$book->updateOrder("catid='$row->catid'");
  //$id = $row->id;*/

  mosRedirect("index2.php?option=$option");


}



/**
* Deletes one or more records
* @param array - An array of unique category id numbers
* @param string - The current author option
*/

function removeMedia($bid, $option) {

	global $database;

	if (!is_array($bid) || count($bid) < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}

	for($i = 0;$i < count($bid); $i++)
	{
		$medialibrary = new mosMedialibrary($database);
		$medialibrary->load(intval($bid[$i]));
		switch ($medialibrary->media_type)
		{

			case 'book':
				$database->setQuery("DELETE FROM #__medialibrary_book WHERE id IN ($medialibrary->media_id)");
				if (!$database->query()) {
				echo "<script> alert('".$database->stderr()."'); window.history.go(-1); </script>\n";
				}
				break;
			case 'video':
				$database->setQuery("DELETE FROM #__medialibrary_video WHERE id IN ($medialibrary->media_id)");
				if (!$database->query()) {
				echo "<script> alert('".$database->stderr()."'); window.history.go(-1); </script>\n";
				}
				break;
			case 'music':
				$database->setQuery("DELETE FROM #__medialibrary_music WHERE id IN ($medialibrary->media_id)");
				if (!$database->query()) {
				echo "<script> alert('".$database->stderr()."'); window.history.go(-1); </script>\n";
				}
				break;
			case 'game':
				$database->setQuery("DELETE FROM #__medialibrary_game WHERE id IN ($medialibrary->media_id)");
				if (!$database->query()) {
				echo "<script> alert('".$database->stderr()."'); window.history.go(-1); </script>\n";
				}
				break;
		}
	}

	$bids = implode(',', $bid);
	$database->setQuery("DELETE FROM #__medialibrary WHERE id IN ($bids)");
	if (!$database->query()) {
	  echo "<script> alert('".$database->stderr()."'); window.history.go(-1); </script>\n";
    exit;
	}
  mosRedirect("index2.php?option=$option");
}


/**
* Publishes or Unpublishes one or more records
* @param array - An array of unique category id numbers
* @param integer - 0 if unpublishing, 1 if publishing
* @param string - The current author option
*/

function publishMedias($bid, $publish, $option) {

	global $database, $my;

	$catid = mosGetParam($_POST, 'catid', array (0));

	if (!is_array($bid) || count($bid) < 1) {
		$action = $publish ? 'publish' : 'unpublish';
		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
		exit;
	}

	$bids = implode(',', $bid);

	$database->setQuery("UPDATE #__medialibrary SET published='$publish'".
	" WHERE id IN ($bids) AND (checked_out=0 OR (checked_out='$my->id'))");

	if (!$database->query()) {
    echo "<script> alert('".$database->stderr()."'); window.history.go(-1); </script>\n";
		exit ();
	}

	if (count($bid) == 1) {
		$row = new mosMediaLibrary($database);
		$row->checkin($bid[0]);
	}

	mosRedirect("index2.php?option=$option");
}

/**
* Moves the order of a record
* @param integer - The increment to reorder by
*/
function orderBooks($bid, $inc, $option) {

	global $database;

	$book = new mosMediaLibrary($database);
	$book->load($bid);
	$book->move($inc);

	mosRedirect("index2.php?option=$option");

}



/**
* Cancels an edit operation
* @param string - The current author option
*/
function cancelEditMedia($option) {

	mosRedirect("index2.php?option=$option");
}

/**
* Refetches the book information
* @param string - The current author option
*/
function refetchInfo($option, $bid) {

	global $database, $my, $medialibrary_configuration;

	$informationFrom = mosGetParam($_POST, 'informationFrom');

	if (!is_array($bid) || count($bid) < 1) {
		echo "<script> alert('Select an item to refetch'); window.history.go(-1);</script>\n";
		exit;
	}

	$bids = implode(',', $bid);

  $selectstring = "SELECT library.id, library.media_type, library.media_id," .
    "cc.title AS category, library.catid, ".
    " library.informationFrom, " .
    " other_table.id as media_type_id,  other_table.title as title  " .
    " FROM #__medialibrary AS library " .
    " LEFT JOIN #__categories AS cc ON cc.id = library.catid "  .
    " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game ".
    " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
    " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
    " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
    " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
    " WHERE library.id IN ($bids) " .
    " ORDER BY library.catid, library.ordering " ;

  $database->setQuery($selectstring);
  $rows = $database->loadObjectList();
//print_r($rows); exit;
  if ($database->getErrorNum()) {
    echo $database->stderr();
    exit ();
  }


//	$database->setQuery("SELECT id, bookid, isbn, title, informationFrom from #__medialibrary WHERE id IN ($bids)");
//	$books = $database->loadObjectList();

	// get list of WS
	$retVal = mosMedialibraryWS :: getWSArray();
	$ws = null;
	for ($i = 0, $n = count($retVal); $i < $n; $i ++) {
		$help = $retVal[$i];
		$ws[] = mosHTML :: makeOption($help[0], $help[1]);
	}

	$wslist = mosHTML :: selectList($ws, 'informationFrom', 'class="inputbox" size="1"', 'value', 'text');
	if ($informationFrom == null) {
		//show fetching information
		HTML_medialibrary :: refetchMedias($option, $rows, $wslist);
	} else {

		//fetching information
		$infos = array ();
		$media_id = array_pop($bid);

		while ($media_id != null) {

      $media = new mosMediaLibrary($database);
      $media->load($media_id);
      $media->informationFrom = $informationFrom;
      $media_tmp = $media;

      $media_type_class = '';
      switch ($media->media_type)
      {
        case 'book':
    
          $media_type_class = new mosMedialibrary_book($database);
          $media_type_class->load($media->media_id);
          //fetch all information from the webservices Amazon WS
          $media_type_class = mosMedialibraryWS :: fetchAmazonInfosForBook($media, $media_type_class);
          $media_type_class_tmp = $media_type_class;

          //check error
          if (is_string($media_type_class)) {
        
            //there was an error while fetching!
            array_push($infos, array ($media_tmp->id, $media_tmp->media_type, 
              $media_type_class_tmp->title, $media_type_class));
          } else {
    
            //storing pictures if neccesary
            $retVal = null;
    
            if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1){
              $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, null);
            }
          }
          break;
        case 'video':
          $media_type_class = new mosMedialibrary_video($database);
          $media_type_class->load($media->media_id);
          //fetch all information from the webservices Amazon WS
          $media_type_class = mosMedialibraryWS :: fetchAmazonInfosForVideo($media, $media_type_class);
          $media_type_class_tmp = $media_type_class;

          //check error
          if (is_string($media_type_class)) {
        
            //there was an error while fetching!
            array_push($infos, array ($media_tmp->id, $media_tmp->media_type, 
              $media_type_class_tmp->title, $media_type_class));
          } else {
    
            //storing pictures if neccesary
            $retVal = null;
    
            if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1){
              $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, null);
            }
          }
          break;
    
        case 'music':
          $media_type_class = new mosMedialibrary_music($database);
          $media_type_class->load($media->media_id);
          //fetch all information from the webservices Amazon WS
          $media_type_class = mosMedialibraryWS :: fetchAmazonInfosForMusic($media, $media_type_class);
          $media_type_class_tmp = $media_type_class;

          //check error
          if (is_string($media_type_class)) {
        
            //there was an error while fetching!
            array_push($infos, array ($media_tmp->id, $media_tmp->media_type, 
              $media_type_class_tmp->title, $media_type_class));
          } else {
    
            //storing pictures if neccesary
            $retVal = null;
    
            if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1){
              $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, null);
            }
          }
          break;
    
        case 'game':
          $media_type_class = new mosMedialibrary_game($database);
          $media_type_class->load($media->media_id);
          //fetch all information from the webservices Amazon WS
          $media_type_class = mosMedialibraryWS :: fetchAmazonInfosForGame($media, $media_type_class);
          $media_type_class_tmp = $media_type_class;

          //check error
          if (is_string($media_type_class)) {
        
            //there was an error while fetching!
            array_push($infos, array ($media_tmp->id, $media_tmp->media_type, 
              $media_type_class_tmp->title, $media_type_class));
          } else {
    
            //storing pictures if neccesary
            $retVal = null;
    
            if(intval($medialibrary_configuration['fetchImages']['boolean']) == 1){
              $retVal = mosMedialibraryOthers :: storeImageFile($media,$media_type_class, null);
            }
          }

       }

        //fetching was OK!
        $media->date = date("Y-m-d H:i:s");
  
        //remove escaped slashes
        if(get_magic_quotes_gpc()) {
          $media_type_class->comment = stripslashes($media_type_class->comment);  
        }

        if ($retVal != null){
          // error storing picture
          array_push($infos, array ($media->id, $media->media_type, $media_type_class->title, $retVal ));
        } else {
           if(!$media_type_class->check() ) {
              array_push($infos, array ($media->id, $media->media_type, $media_type_class->title,
                   $media_type_class->getError()));
            } else {
              if (!$media->check()) {
                array_push($infos, array ($media->id, $media->media_type, $media_type_class->title,
                   $media->getError()));
              } else {
                if (!$media_type_class->store()) {
                  array_push($infos, array ($media->id, $media->media_type, $media_type_class->title,
                      $media_type_class->getError()));
                }else{
                  $media->media_id = $media_type_class->id;
                
                  if (!$media->store()) {
                    array_push($infos, array ($media->id, $media->media_type, $media_type_class->title,
                      $media->getError()));
                  }
                  array_push($infos, array ($media->id, $media->media_type, $media_type_class->title, "OK"));
                }
              }
            }
        }
        $media->checkin();
        $media_id = array_pop($bid);
      }

		$infos = array_reverse($infos);

		HTML_medialibrary :: showInfoRefetchMedias($option, $infos, $wslist);
  }
}

function configure_save_frontend($option){
	global $my, $medialibrary_configuration;

	$str = '';
	$supArr = array();
	$supArr = mosGetParam($_POST, 'emedias_registrationlevel', 0);
	for($i = 0;$i<count($supArr);$i++)
	$str.=$supArr[$i].',';
	$str = substr($str,0,-1);
	$medialibrary_configuration['emedias']['registrationlevel']=$str;

	$str = '';
	$supArr = mosGetParam($_POST, 'reviews_registrationlevel', 0);
	for($i = 0;$i<count($supArr);$i++)
	$str.=$supArr[$i].',';
	$str = substr($str,0,-1);
	$medialibrary_configuration['reviews']['registrationlevel']=$str;

	$str = '';
	$supArr = mosGetParam($_POST, 'lendrequest_registrationlevel', 0);
	for($i = 0;$i<count($supArr);$i++)
	$str.=$supArr[$i].',';
	$str = substr($str,0,-1);
	$medialibrary_configuration['lendrequest']['registrationlevel']=$str;


	$medialibrary_configuration['reviews']['show']= mosGetParam($_POST, 'reviews_show', 0);
	$medialibrary_configuration['lendstatus']['show']=mosGetParam($_POST, 'lendstatus_show', 0);
	$medialibrary_configuration['emedias']['show']= mosGetParam($_POST, 'emedias_show', 0);
	$medialibrary_configuration['price']['show']= mosGetParam($_POST, 'price_show', 0);
	$medialibrary_configuration['foto']['high']=mosGetParam($_POST, 'foto_high');
	$medialibrary_configuration['foto']['width']=mosGetParam($_POST, 'foto_width');
	$medialibrary_configuration['page']['items']=mosGetParam($_POST, 'page_items');
	//add for show in category picture
	$medialibrary_configuration['cat_pic']['show'] = mosGetParam($_POST, 'cat_pic_show');

	//add for show subcategory
	$medialibrary_configuration['subcategory']['show'] = mosGetParam($_POST, 'subcategory_show');



	mosMedialibraryOthers :: setParams();

	configure_frontend($option);
}

function configure_save_backend($option){

	global $my, $medialibrary_configuration;

	$medialibrary_configuration['fetchImages']['boolean']= mosGetParam($_POST, 'fetchImages_boolean', 0);
	$medialibrary_configuration['fetchImages']['location']= mosGetParam($_POST, 'fetchImages_location', "/components/com_medialibrary/covers/");
	$medialibrary_configuration['emedias']['allow']= mosGetParam($_POST, 'emedias_allow', 0);
	$medialibrary_configuration['emedias']['location']= mosGetParam($_POST, 'emedias_location', "/components/com_medialibrary/ebooks/");
	$medialibrary_configuration['ws']['amazon']['tag']=mosGetParam($_POST, 'ws_amazon_tag', "gerdsaurer-20");
	$medialibrary_configuration['ws']['amazon']['devtag']=mosGetParam($_POST, 'ws_amazon_devtag');
	$medialibrary_configuration['editmedia']['check']['isbn_asin'] = mosGetParam($_POST, 'editmedia_check_isbn_asin', 0);
	$medialibrary_configuration['editmedia']['default']['lang'] = mosGetParam($_POST, 'editmedia_default_lang', 0);

	mosMedialibraryOthers :: setParams();

	configure_backend($option);
}

function configure_frontend($option)
{

	global $my, $medialibrary_configuration, $acl,$database;

	$yesno[] = mosHTML :: makeOption('1', _MEDIALIBRARY_YES);
	$yesno[] = mosHTML :: makeOption('0', _MEDIALIBRARY_NO);

	$gtree[] = mosHTML :: makeOption('-2', 'Everyone');
	$gtree = array_merge($gtree, $acl->get_group_children_tree( null, 'USERS', false ));

	$lists = array ();
	$f="";
	$s = explode(',',$medialibrary_configuration['reviews']['registrationlevel']);
	for($i = 0;$i<count($s);$i++)
	$f[] = mosHTML::makeOption( $s[$i] );

	$lists['reviews']['show'] = mosHTML :: RadioList($yesno, 'reviews_show', 'class="inputbox"', $medialibrary_configuration['reviews']['show'], 'value', 'text');
	$lists['reviews']['registrationlevel'] = mosHTML::selectList( $gtree, 'reviews_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f);

	$f="";
	$s = explode(',',$medialibrary_configuration['lendrequest']['registrationlevel']);
	for($i = 0;$i<count($s);$i++)
	$f[] = mosHTML::makeOption( $s[$i] );

	$lists['lendstatus']['show'] = mosHTML :: RadioList($yesno, 'lendstatus_show', 'class="inputbox"', $medialibrary_configuration['lendstatus']['show'], 'value', 'text');

	$lists['lendrequest']['registrationlevel'] = mosHTML::selectList( $gtree, 'lendrequest_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f );

	$f="";
	$s = explode(',',$medialibrary_configuration['emedias']['registrationlevel']);
	for($i = 0;$i<count($s);$i++)
	$f[] = mosHTML::makeOption( $s[$i] );

	$lists['emedias']['registrationlevel'] = mosHTML::selectList( $gtree, 'emedias_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f );

	$lists['emedias']['show'] = mosHTML :: RadioList($yesno, 'emedias_show', 'class="inputbox"', $medialibrary_configuration['emedias']['show'], 'value', 'text');


	$lists['price']['show'] = mosHTML :: RadioList($yesno, 'price_show', 'class="inputbox"', $medialibrary_configuration['price']['show'], 'value', 'text');


	$lists['foto']['high'] = '<input type="text" name="foto_high" value="'.$medialibrary_configuration['foto']['high'].'" class="inputbox" size="4" maxlength="4" title="" />';

	$lists['foto']['width'] = '<input type="text" name="foto_width" value="'.$medialibrary_configuration['foto']['width'].'" class="inputbox" size="4" maxlength="4" title="" />';

	$lists['page']['items'] = '<input type="text" name="page_items" value="'.$medialibrary_configuration['page']['items'].'" class="inputbox" size="2" maxlength="2" title="" />';

	//add for show in category picture
	$lists['cat_pic']['show'] = mosHTML :: RadioList($yesno, 'cat_pic_show', 'class="inputbox"', $medialibrary_configuration['cat_pic']['show'], 'value', 'text');


	//add for show subcategory
	$lists['subcategory']['show'] = mosHTML :: RadioList($yesno, 'subcategory_show', 'class="inputbox"', $medialibrary_configuration['subcategory']['show'], 'value', 'text');




	HTML_medialibrary :: showConfiguration_frontend($lists, $option);
}


function configure_backend($option) {

	global $my, $medialibrary_configuration, $acl;


	$yesno[] = mosHTML :: makeOption('1', _MEDIALIBRARY_YES);
	$yesno[] = mosHTML :: makeOption('0', _MEDIALIBRARY_NO);

	$gtree[] = mosHTML :: makeOption('-2', 'Everyone');
	$gtree = array_merge($gtree, $acl->get_group_children_tree( null, 'USERS', false ));

	$lists = array ();

	$lists['fetchImages']['boolean'] = mosHTML :: RadioList($yesno, 'fetchImages_boolean', 'class="inputbox"', $medialibrary_configuration['fetchImages']['boolean'], 'value', 'text');

	$lists['fetchImages']['location'] = '<input type="text" name="fetchImages_location" value="'.$medialibrary_configuration['fetchImages']['location'].'" class="inputbox" size="50" maxlength="50" title="" />';
	$lists['emedias']['allow'] = mosHTML :: RadioList($yesno, 'emedias_allow', 'class="inputbox"', $medialibrary_configuration['emedias']['allow'], 'value', 'text');

	$lists['emedias']['location'] = '<input type="text" name="emedias_location" value="'.$medialibrary_configuration['emedias']['location'].'" class="inputbox" size="50" maxlength="50" title="" />';

	$lists['ws']['amazon']['tag'] = '<input type="text" name="ws_amazon_tag" value="'.$medialibrary_configuration['ws']['amazon']['tag'].'" class="inputbox" size="50" maxlength="50" title="" />';

	$lists['ws']['amazon']['devtag'] = '<input type="text" name="ws_amazon_devtag" value="'.$medialibrary_configuration['ws']['amazon']['devtag'].'" class="inputbox" size="50" maxlength="50" title="" />';

	@$lists['editmedia']['check']['isbn_asin'] = mosHTML :: RadioList($yesno, 'editmedia_check_isbn_asin', 'class="inputbox"', $medialibrary_configuration['editmedia']['check']['isbn_asin'], 'value', 'text');//back--7


	//get language List
	$retVal1 = mosMedialibraryOthers :: getLanguageArray();
	$lang = null;
	for ($i = 0, $n = count($retVal1); $i < $n; $i ++) {

		$help = & $retVal1[$i];
		$lang[] = mosHTML :: makeOption($help[0], $help[1]);
	}
	$lists['editmedia']['default']['lang'] = mosHTML :: selectList($lang, 'editmedia_default_lang', 'class="inputbox" size="1"', 'value', 'text', $medialibrary_configuration['editmedia']['default']['lang']);

	//get host List
	$retVal = mosMedialibraryWS :: getArray();
	$ws = null;
	for ($i = 0, $n = count($retVal); $i < $n; $i ++) {

		$help = & $retVal[$i];
		$ws[] = mosHTML :: makeOption($help[0], $help[1]);

	}

	$lists['emedias']['registrationlevel'] = mosHTML::selectList( $gtree, 'emedias_registrationlevel', 'size="4"', 'value', 'text', $my->gid );//(rus)--i tam i tam nado navernoe!


	HTML_medialibrary :: showConfiguration_backend($lists, $option );
}
//*****************************   end  moe   *********************




function lend($option, $bid)
{

	global $database, $my;

	if (!is_array($bid) || count($bid) < 1) {
		echo "<script> alert('Select an item to lend'); window.history.go(-1);</script>\n";
		exit;
	}

	$bids = implode(',', $bid);


  $selectstring = "SELECT library.id, library.media_type, library.media_id," .
    "cc.title AS category, library.catid, ".
    " l.id as lendid, l.lend_from as lend_from, " .
    " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
    " l.lend_until as lend_until, l.user_name as user_name ," .
    " l.user_email AS user_email, l.fk_userid as fk_userid ," .
    " other_table.id as media_type_id,  other_table.title as title  " .
    " FROM #__medialibrary AS library " .
    " LEFT JOIN #__categories AS cc ON cc.id = library.catid "  .
    " LEFT JOIN #__medialibrary_lend AS l ON l.id = library.fk_lendid".
    " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game ".
    " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
    " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
    " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
    " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
    " WHERE library.id in (".$bids.")";
  $database->setQuery( $selectstring );

	if (!$database->query()) {
		echo "<script> alert('".$database->getError()."'); window.history.go(-1); </script>\n";
		exit ();
	}

	$medias = $database->loadObjectList();


	// get list of categories
	$userlist[] = mosHTML :: makeOption('-1', '----------');
	$database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
	$userlist = array_merge($userlist, $database->loadObjectList());
	$usermenu = mosHTML :: selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');

	HTML_medialibrary :: showLendMedias($option, $medias, $usermenu, "lend");
}

function lend_return($option, $bid)
{

	global $database, $my;
	if (!is_array($bid) || count($bid) < 1) {
		echo "<script> alert('Select an item to lend'); window.history.go(-1);</script>\n";
		exit;
	}
	$bids = implode(',', $bid);


  $selectstring = "SELECT l.id, library.media_type, library.media_id," .
    "cc.title AS category, library.catid, ".
    " l.id as lendid, l.lend_from as lend_from, " .
    " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
    " l.lend_until as lend_until, l.user_name as user_name ," .
    " l.user_email as user_email, l.fk_userid as fk_userid ," .
    " other_table.id as media_type_id,  other_table.title as title  " .
    " FROM #__medialibrary_lend AS l, #__medialibrary AS library " .
    " LEFT JOIN #__categories AS cc ON cc.id = library.catid "  .
    " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game ".
    " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
    " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
    " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
    " AS other_table ON other_table.id = library.media_id and other_table.type = library.media_type" .
    " WHERE l.id = library.fk_lendid and library.id in (".$bids.")";
  $database->setQuery( $selectstring );

	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit ();
	}

	$medias = $database->loadObjectList();

	$count=count($medias);
	for($i=0;$i<1;$i++)
	{
		if((($medias[$i]->lend_from)=='')&&(($medias[$i]->lend_return)==''))
		{
			/*
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
			exit ();
			*/

       ?>
       <script type = "text/JavaScript" language = "JavaScript">
       alert('You cannot return medias that were not lent out');
       window.history.go(-1);
       </script>
       <?php 
       exit;
		}
	}
	// get list of users
	$userlist[] = mosHTML :: makeOption('-1', '----------');
	$database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
	$userlist = array_merge($userlist, $database->loadObjectList());
	$usermenu = mosHTML :: selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');

	HTML_medialibrary :: showLendMedias($option, $medias, $usermenu, "lend_return");
}

function saveLend($option, $bids) {

	global $database, $my;

	if (!is_array($bids) || count($bids) < 1) {
		echo "<script> alert('Select an item to lend'); window.history.go(-1);</script>\n";
		exit;
	}

	for ($i = 0, $n = count($bids); $i < $n; $i ++) {
		$id = $bids[$i];
		$lend = new mosMediaLibrary_lend($database);

		$lend->lend_from = date("Y-m-d H:i:s");
		if (mosGetParam($_POST, 'lend_until') != "") {
			$lend->lend_until = mosGetParam($_POST, 'lend_until');
		} else {
			$lend->lend_until = null;
		}

		$lend->fk_mediaid = $id;

		$userid = mosGetParam($_POST, 'userid');
		if ($userid == "-1") {
			$lend->user_name = mosGetParam($_POST, 'user_name', '');
			$lend->user_email = mosGetParam($_POST, 'user_email', '');
		} else {
			$lend->fk_userid = intval($userid);
      $selectstring = "SELECT name, email FROM #__users  ".
       " WHERE  id = ".$lend->fk_userid;
      $database->setQuery($selectstring);
      $row = $database->loadObjectList();
      if ($database->getErrorNum()) {
        echo $database->stderr();
        return;
      }
      $lend->user_name = $row[0]->name;
      $lend->user_email = $row[0]->email;

		}

		if (!$lend->check($lend)) {
			echo "<script> alert('".$lend->getError()."'); window.history.go(-1); </script>\n";
			exit ();
		}

		if (!$lend->store()) {

			echo "<script> alert('".$lend->getError()."'); window.history.go(-1); </script>\n";

			exit ();

		}
		$lend->checkin();
		$media = new mosMediaLibrary($database);
		$media->load($id);
		$media->fk_lendid = $lend->id;
		$media->store();
		$media->checkin();

	}
	mosRedirect("index2.php?option=$option");

}

function saveLend_return($option, $lids) {

	global $database, $my;

	if (!is_array($lids) || count($lids) < 1) {

		echo "<script> alert('Select an item to return'); window.history.go(-1);</script>\n";

		exit;

	}
	for ($i = 0, $n = count($lids); $i < $n; $i ++) {
		$id = $lids[$i];
		$lend = new mosMediaLibrary_lend($database);
		$lend->load(intval($id));
		$lend->lend_return = date("Y-m-d H:i:s");
		if (!$lend->check($lend)) {

			echo "<script> alert('".$lend->getError()."'); window.history.go(-1); </script>\n";

			exit ();

		}

		if (!$lend->store()) {

			echo "<script> alert('".$lend->getError()."'); window.history.go(-1); </script>\n";

			exit ();

		}
		$lend->checkin();
		$book = new mosMediaLibrary($database);
		$book->load($lend->fk_mediaid);
		$book->fk_lendid = 0;
		$book->store(true);
		$book->checkin(true);
	}
	mosRedirect("index2.php?option=$option");
}



function import($option)
{


	global $database, $my;

	$file = file($_FILES['import_file']['tmp_name']);
	$catid = mosGetParam($_POST, 'import_catid');

	//***********************   begin add for XML format   ***************************************
	$type = mosGetParam($_POST, 'import_type');
	switch($type)
	{
		//CSV=='1' XML=='2'
		case '1':
			$retVal = mosMediaLibraryImportExport :: importMediasCSV($file, $catid);
			HTML_medialibrary:: showImportResult($retVal, $option);
			break;

		case '2':
      $retVal = mosMediaLibraryImportExport :: importMediasXML($_FILES['import_file']['tmp_name'], $catid);
			HTML_medialibrary:: showImportResult($retVal, $option);
			break;

		case '3':
      $ret = mosMediaLibraryImportExport::remove_info();
      if( $ret != "" ) return;
      $retVal = mosMediaLibraryImportExport :: importMediasXML($_FILES['import_file']['tmp_name'],null);
      HTML_medialibrary:: showImportResult($retVal, $option);
//			$retVal = mosMediaLibraryImportExport :: entire_import($_FILES['import_file']['tmp_name']);
			break;
			//***********************   end add for XML format   *****************************************
	}
}



function export($option) {
	global $database, $my, $mainframe;
// 	if($_POST['export_type'] == 3)
// 	{
// 		$InformationArray = mosMediaLibraryImportExport :: entire_export();
// 		HTML_medialibrary :: showExportResult($InformationArray, $option);
// 
// 	}
// 	else
//	{
		$catid = mosGetParam($_POST, 'export_catid', 0);
		$lend = mosGetParam($_POST, 'export_lend', null);
		$pub = mosGetParam($_POST, 'export_pub', null);
		$type = mosGetParam($_POST, 'export_type', 0);

		$search = $mainframe->getUserStateFromRequest("search{$option}", 'search', '');
		$search = $database->getEscaped(trim(strtolower($search)));

		$where = array ();

		if ($lend == "lend") {
			array_push($where, " a.fk_lendid <> 0 ");
		} else if ($lend == "not_lend") {
			array_push($where, " a.fk_lendid = 0 ");
		}
		if ($pub== "pub") {
			array_push($where, " a.published = 1 ");
		} else if ($pub == "not_pub") {
			array_push($where, " a.published = 0 ");
		}
		if ($catid > 0) {
			array_push($where, " a.catid='$catid' ");
		}

		if ($search) {
			array_push($where, "(LOWER(a.title) LIKE '%$search%' OR LOWER(a.authors) LIKE '%$search%' OR LOWER(a.isbn) LIKE '%$search%' OR LOWER(a.comment) LIKE '%$search%')");
		}

		$selectstring = "SELECT a.id FROM #__medialibrary AS a,  #__categories as c ".
		" WHERE c.id = a.catid " . (count($where) ? ' AND ' . implode(' AND ', $where) : "").
		" ORDER BY c.parent_id, c.id, a.ordering";
		$database->setQuery($selectstring);
		$bids = $database->loadObjectList();

		if ($database->getErrorNum()) {
			echo $database->stderr();
			return;
		}

		$medias = array();
		$count = 0;
		foreach($bids as $bid){
			$media = new mosMediaLibrary($database);
			// load the row from the db table
			$media->load(intval($bid->id));
			$medias[$count] = $media;
			$count++;
		}


		// begin add for Export XML all record
		//move to xml - all data
		$retVal = mosMediaLibraryImportExport :: exportMediasXML($medias);


		$type2 = 'xml';
		switch ($type) {
			case '1':
				$type2 = 'csv';
				break;
		}

		$InformationArray = mosMediaLibraryImportExport :: storeExportFile($retVal, $type2);

		HTML_medialibrary :: showExportResult($InformationArray, $option);
//	}
}



function importExport($option) {
	global $database;

	// get list of categories
	$categories[] = mosHTML :: makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
	$database->setQuery("SELECT id AS value, name AS text FROM #__categories"."\nWHERE section='$option' ORDER BY ordering");
	$categories = array_merge($categories, $database->loadObjectList());

	if (count($categories) < 1) {
		mosRedirect("index2.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
	}

	$impclist = mosHTML :: selectList($categories, 'import_catid', 'class="inputbox" size="1" id="import_catid"', 'value', 'text', 0);
	$expclist = mosHTML :: selectList($categories, 'export_catid', 'class="inputbox" size="1" id="export_catid"', 'value', 'text', 0);

	$params = array();
	$params['import']['category'] = $impclist;
	$params['export']['category'] = $expclist;

	$importtypes[0] = mosHTML :: makeOption('0', _MEDIALIBRARY_ADMIN_PLEASE_SEL);
//	$importtypes[1] = mosHTML :: makeOption('1', _MEDIALIBRARY_ADMIN_FORMAT_CSV);
	$importtypes[2] = mosHTML :: makeOption('2', _MEDIALIBRARY_ADMIN_FORMAT_XML);
	$importtypes[3] = mosHTML :: makeOption('3', _MEDIALIBRARY_ADMIN_ENTIRE_RECOVER);

	$params['import']['type'] = mosHTML :: selectList($importtypes, 'import_type', 'id="import_type" class="inputbox" size="1" onchange = "impch();"', 'value', 'text', 0);

	$exporttypes[0] = mosHTML :: makeOption('0', _MEDIALIBRARY_ADMIN_PLEASE_SEL);
//	$exporttypes[1] = mosHTML :: makeOption('1', _MEDIALIBRARY_ADMIN_FORMAT_CSV);
	$exporttypes[2] = mosHTML :: makeOption('2', _MEDIALIBRARY_ADMIN_FORMAT_XML);
	$exporttypes[3] = mosHTML :: makeOption('3', _MEDIALIBRARY_ADMIN_ENTIRE_BU);

	$params['export']['type'] = mosHTML :: selectList($exporttypes, 'export_type', 'id="export_type" class="inputbox" size="1" onchange="expch();"', 'value', 'text', 0);

	HTML_medialibrary :: showImportExport($params, $option);
}

// отрисовка некоторых eлементов игры
function editing_game($media_class, $medialibrary, $option, $bid)
{

  global $database, $my, $mosConfig_live_site, $medialibrary_configuration;

  $is_new = false;
  if($bid === 0) {
    $is_new = true;
  }

  // вставка категорий
  $categories[] = mosHTML :: makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
  $database->setQuery("SELECT id AS value, name AS text FROM #__categories".
    " WHERE section='$option' ORDER BY ordering ");
  $categories = array_merge($categories, $database->loadObjectList());
  if (count($categories) <= 1)
  {
    mosRedirect("index2.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
  }
  $clist = mosHTML :: selectList($categories, 'catid', 'class="inputbox" size="1"', 
    'value', 'text', intval($medialibrary->catid));

  // вставка амазона
  $retVal = mosMedialibraryWS :: getArray();
  $ws = null;
  for ($i = 0, $n = count($retVal); $i < $n; $i ++)
  {
    $help = & $retVal[$i];
    $ws[] = mosHTML :: makeOption($help[0], $help[1]);
  }
  if($bid == 0)
    $wslist = mosHTML :: selectList($ws, 'informationFrom', 'class="inputbox" size="1"',
     'value', 'text', 0 );
  else
    $wslist = mosHTML :: selectList($ws, 'informationFrom', 'class="inputbox" size="1"',
     'value', 'text', intval($medialibrary->informationFrom));

  // выбор языка
  $retVal1 = mosMedialibraryOthers :: getLanguageArray();
  $lang = null;
  for ($i = 0, $n = count($retVal1); $i < $n; $i++)
  {
    $help = & $retVal1[$i];
    $lang[] = mosHTML :: makeOption($help[0], $help[1]);
  }
  if($bid == 0)
    $langlist = mosHTML :: selectList($lang, 'language', 'class="inputbox" size="1"',
       'value', 'text', $medialibrary_configuration['editmedia']['default']['lang'] );
  else
    $langlist = mosHTML :: selectList($lang, 'language', 'class="inputbox" size="1"',
       'value', 'text', $media_class->language);

  // выбор рейтинга
  $retVal2 = mosMedialibraryOthers :: getRatingArray();
  $rating = null;
  for ($i = 0, $n = count($retVal2); $i < $n; $i ++)
  {
    $help = & $retVal2[$i];
    $rating[] = mosHTML :: makeOption($help[0], $help[1]);
  }
  $ratinglist = mosHTML :: selectList($rating, 'rating', 'class="inputbox" size="1"',
     'value', 'text', $media_class->rating);

  // выбор типа
  $type_list = mosMedialibraryOthers :: getTypeArray();
  $type = null;
  foreach ($type_list as $value)
  {
    $help = & $value;
    $type[] = mosHTML :: makeOption($help[0], $help[1]);
  }

  if($is_new){
    $type_list = mosHTML :: selectList($type, 'media_type', 
      'class="inputbox" size="1" onchange="type_select();" ', 'value', 'text',
      $medialibrary->media_type);
  } else{
    $type_list = mosHTML :: selectList($type, 'media_type', 
      'class="inputbox" size="1" onchange="type_select();" disabled="true"', 'value', 'text',
      $medialibrary->media_type);
  }

  // delete egame?
  $help = str_replace($mosConfig_live_site, "", $media_class->egameURL);
  $delete_edocument_yesno[] = mosHTML :: makeOption($help, _MEDIALIBRARY_YES);
  $delete_edocument_yesno[] = mosHTML :: makeOption('0', _MEDIALIBRARY_NO);
  $delete_edocument = mosHTML :: RadioList($delete_edocument_yesno, 'delete_edocument', 'class="inputbox"', '0', 'value', 'text');
  // fail if checked out not by 'me'
  if ($medialibrary->checked_out && $medialibrary->checked_out != $my->id)
  {
    mosRedirect("index2.php?option=$option", _MEDIALIBRARY_IS_EDITED);
  }
  if ($bid)
  {
    $medialibrary->checkout($my->id);
  }
  else
  {
    // initialise new record
    $medialibrary->published = 0;
    $medialibrary->approved = 0;
  }

	//*****************************   begin for reviews **************************//
	$database->setQuery("SELECT a.*, b.name FROM #__medialibrary_review a, #__users b".
	" WHERE a.fk_userid = b.id and a.fk_mediaid=".$bid." ORDER BY date ;");

	$reviews1 = $database->loadObjectList();

	//take review for anonymous users
	$database->setQuery("select a.*, 'anonymous' as name from #__medialibrary_review a  ".
	" WHERE a.fk_userid = 0 and a.fk_mediaid = ".$bid." ORDER BY date ;");
	$reviews2 = $database->loadObjectList();

	$reviews = array_merge($reviews1, $reviews2);

	//**********************   end for reviews   *****************************//
	$multimedia_type = 'game';
	HTML_medialibrary :: editMedia($option,$medialibrary, $media_class, $clist, $wslist, $langlist, $ratinglist, 
    $delete_edocument, $reviews, $type_list, $multimedia_type);

}

// отрисовка некоторых eлементов музыки
function editing_music($media_class, $medialibrary, $option, $bid)
{
	global $database, $my, $mosConfig_live_site, $medialibrary_configuration;

  $is_new = false;
  if($bid === 0) {
    $is_new = true;
  }

  // вставка категорий
  $categories[] = mosHTML :: makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
  $database->setQuery("SELECT id AS value, name AS text FROM #__categories".
    " WHERE section='$option' ORDER BY ordering ");
  $categories = array_merge($categories, $database->loadObjectList());
  if (count($categories) <= 1)
  {
    mosRedirect("index2.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
  }
  $clist = mosHTML :: selectList($categories, 'catid', 'class="inputbox" size="1"', 
    'value', 'text', intval($medialibrary->catid));

  // вставка амазона
  $retVal = mosMedialibraryWS :: getArray();
  $ws = null;
  for ($i = 0, $n = count($retVal); $i < $n; $i ++)
  {
    $help = & $retVal[$i];
    $ws[] = mosHTML :: makeOption($help[0], $help[1]);
  }
  if($bid == 0)
    $wslist = mosHTML :: selectList($ws, 'informationFrom', 'class="inputbox" size="1"',
     'value', 'text', 0 );
  else
    $wslist = mosHTML :: selectList($ws, 'informationFrom', 'class="inputbox" size="1"',
     'value', 'text', intval($medialibrary->informationFrom));

  // выбор языка
  $retVal1 = mosMedialibraryOthers :: getLanguageArray();
  $lang = null;
  for ($i = 0, $n = count($retVal1); $i < $n; $i++)
  {
    $help = & $retVal1[$i];
    $lang[] = mosHTML :: makeOption($help[0], $help[1]);
  }
  if($bid == 0)
    $langlist = mosHTML :: selectList($lang, 'language', 'class="inputbox" size="1"',
       'value', 'text', $medialibrary_configuration['editmedia']['default']['lang'] );
  else
    $langlist = mosHTML :: selectList($lang, 'language', 'class="inputbox" size="1"',
       'value', 'text', $media_class->language);

  // выбор рейтинга
  $retVal2 = mosMedialibraryOthers :: getRatingArray();
  $rating = null;
  for ($i = 0, $n = count($retVal2); $i < $n; $i ++)
  {
    $help = & $retVal2[$i];
    $rating[] = mosHTML :: makeOption($help[0], $help[1]);
  }
  $ratinglist = mosHTML :: selectList($rating, 'rating', 'class="inputbox" size="1"',
     'value', 'text', $media_class->rating);

  // выбор типа
  $type_list = mosMedialibraryOthers :: getTypeArray();
  $type = null;
  foreach ($type_list as $value)
  {
    $help = & $value;
    $type[] = mosHTML :: makeOption($help[0], $help[1]);
  }

  if($is_new){
    $type_list = mosHTML :: selectList($type, 'media_type', 
      'class="inputbox" size="1" onchange="type_select();" ', 'value', 'text',
      $medialibrary->media_type);
  } else{
    $type_list = mosHTML :: selectList($type, 'media_type', 
      'class="inputbox" size="1" onchange="type_select();" disabled="true"', 'value', 'text',
      $medialibrary->media_type);
  }

  // delete emusic?
  $help = str_replace($mosConfig_live_site, "", $media_class->emusicURL);
  $delete_edocument_yesno[] = mosHTML :: makeOption($help, _MEDIALIBRARY_YES);
  $delete_edocument_yesno[] = mosHTML :: makeOption('0', _MEDIALIBRARY_NO);
  $delete_edocument = mosHTML :: RadioList($delete_edocument_yesno, 'delete_edocument', 'class="inputbox"', '0', 'value', 'text');
  // fail if checked out not by 'me'
  if ($medialibrary->checked_out && $medialibrary->checked_out != $my->id)
  {
    mosRedirect("index2.php?option=$option", _MEDIALIBRARY_IS_EDITED);
  }
  if ($bid)
  {
    $medialibrary->checkout($my->id);
  }
  else
  {
    // initialise new record
    $medialibrary->published = 0;
    $medialibrary->approved = 0;
  }

	//*****************************   begin for reviews **************************//
	$database->setQuery("SELECT a.*, b.name FROM #__medialibrary_review a, #__users b".
	" WHERE a.fk_userid = b.id and a.fk_mediaid=".$bid." ORDER BY date ;");

	$reviews1 = $database->loadObjectList();

	//take review for anonymous users
	$database->setQuery("select a.*, 'anonymous' as name from #__medialibrary_review a  ".
	" WHERE a.fk_userid = 0 and a.fk_mediaid = ".$bid." ORDER BY date ;");
	$reviews2 = $database->loadObjectList();

	$reviews = array_merge($reviews1, $reviews2);

	//**********************   end for reviews   *****************************//
	$multimedia_type = 'music';
	HTML_medialibrary :: editMedia($option,$medialibrary, $media_class, $clist, $wslist, $langlist, $ratinglist, 
    $delete_edocument, $reviews, $type_list, $multimedia_type);
}
// отрисовка некоторых eлементов видео
function editing_video($media_class, $medialibrary, $option, $bid)
{
	global $database, $my, $mosConfig_live_site, $medialibrary_configuration;
	
  $is_new = false;
  if($bid === 0) {
    $is_new = true;
  }

  // вставка категорий
  $categories[] = mosHTML :: makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
  $database->setQuery("SELECT id AS value, name AS text FROM #__categories".
    " WHERE section='$option' ORDER BY ordering ");
  $categories = array_merge($categories, $database->loadObjectList());
  if (count($categories) <= 1)
  {
    mosRedirect("index2.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
  }
  $clist = mosHTML :: selectList($categories, 'catid', 'class="inputbox" size="1"', 
    'value', 'text', intval($medialibrary->catid));

  // вставка амазона
  $retVal = mosMedialibraryWS :: getArray();
  $ws = null;
  for ($i = 0, $n = count($retVal); $i < $n; $i ++)
  {
    $help = & $retVal[$i];
    $ws[] = mosHTML :: makeOption($help[0], $help[1]);
  }
  if($bid == 0)
    $wslist = mosHTML :: selectList($ws, 'informationFrom', 'class="inputbox" size="1"',
     'value', 'text', 0 );
  else
    $wslist = mosHTML :: selectList($ws, 'informationFrom', 'class="inputbox" size="1"',
     'value', 'text', intval($medialibrary->informationFrom));

  // выбор языка
  $retVal1 = mosMedialibraryOthers :: getLanguageArray();
  $lang = null;
  for ($i = 0, $n = count($retVal1); $i < $n; $i++)
  {
    $help = & $retVal1[$i];
    $lang[] = mosHTML :: makeOption($help[0], $help[1]);
  }
  if($bid == 0)
    $langlist = mosHTML :: selectList($lang, 'language', 'class="inputbox" size="1"',
       'value', 'text', $medialibrary_configuration['editmedia']['default']['lang'] );
  else
    $langlist = mosHTML :: selectList($lang, 'language', 'class="inputbox" size="1"',
       'value', 'text', $media_class->language);

  // выбор рейтинга
  $retVal2 = mosMedialibraryOthers :: getRatingArray();
  $rating = null;
  for ($i = 0, $n = count($retVal2); $i < $n; $i ++)
  {
    $help = & $retVal2[$i];
    $rating[] = mosHTML :: makeOption($help[0], $help[1]);
  }
  $ratinglist = mosHTML :: selectList($rating, 'rating', 'class="inputbox" size="1"',
     'value', 'text', $media_class->rating);

  // выбор типа
  $type_list = mosMedialibraryOthers :: getTypeArray();
  $type = null;
  foreach ($type_list as $value)
  {
    $help = & $value;
    $type[] = mosHTML :: makeOption($help[0], $help[1]);
  }

  if($is_new){
    $type_list = mosHTML :: selectList($type, 'media_type', 
      'class="inputbox" size="1" onchange="type_select();" ', 'value', 'text',
      $medialibrary->media_type);
  } else{
    $type_list = mosHTML :: selectList($type, 'media_type', 
      'class="inputbox" size="1" onchange="type_select();" disabled="true"', 'value', 'text',
      $medialibrary->media_type);
  }
	
	// delete evideo?
	$help = str_replace($mosConfig_live_site, "", $media_class->evideoURL);
	$delete_edocument_yesno[] = mosHTML :: makeOption($help, _MEDIALIBRARY_YES);
	$delete_edocument_yesno[] = mosHTML :: makeOption('0', _MEDIALIBRARY_NO);
	$delete_edocument = mosHTML :: RadioList($delete_edocument_yesno, 'delete_edocument', 'class="inputbox"', '0', 'value', 'text');
	// fail if checked out not by 'me'
	if ($medialibrary->checked_out && $medialibrary->checked_out != $my->id)
	{
		mosRedirect("index2.php?option=$option", _MEDIALIBRARY_IS_EDITED);
	}
	if ($bid)
	{
		$medialibrary->checkout($my->id);
	}
	else
	{
		// initialise new record
		$medialibrary->published = 0;
		$medialibrary->approved = 0;
	}
	//*****************************   begin for reviews **************************//
	$database->setQuery("SELECT a.*, b.name FROM #__medialibrary_review a, #__users b".
	" WHERE a.fk_userid = b.id and a.fk_mediaid=".$bid." ORDER BY date ;");

	$reviews1 = $database->loadObjectList();

	//take review for anonymous users
	$database->setQuery("select a.*, 'anonymous' as name from #__medialibrary_review a  ".
	" WHERE a.fk_userid = 0 and a.fk_mediaid = ".$bid." ORDER BY date ;");
	$reviews2 = $database->loadObjectList();

	$reviews = array_merge($reviews1, $reviews2);

	//**********************   end for reviews   *****************************//
	$multimedia_type = 'video';
	HTML_medialibrary :: editMedia($option,$medialibrary, $media_class, $clist, $wslist, $langlist, $ratinglist, $delete_edocument, $reviews, $type_list, $multimedia_type);

}

// отрисовка некоторых eлементов книги
function editing_book($media_class, $medialibrary, $option, $bid)
{
	global $database, $my, $mosConfig_live_site, $medialibrary_configuration;

  $is_new = false;
  if($bid === 0) {
    $is_new = true;
  }

	// вставка категорий
	$categories[] = mosHTML :: makeOption('0', _MEDIALIBRARY_LABEL_SELECT_CATEGORIES);
	$database->setQuery("SELECT id AS value, name AS text FROM #__categories".
    " WHERE section='$option' ORDER BY ordering ");
	$categories = array_merge($categories, $database->loadObjectList());
	if (count($categories) <= 1)
	{
		mosRedirect("index2.php?option=com_medialibrary&section=categories", _MEDIALIBRARY_ADMIN_IMPEXP_ADD);
	}
	$clist = mosHTML :: selectList($categories, 'catid', 'class="inputbox" size="1"', 
    'value', 'text', intval($medialibrary->catid));

	// вставка амазона
	$retVal = mosMedialibraryWS :: getArray();
	$ws = null;
	for ($i = 0, $n = count($retVal); $i < $n; $i ++)
	{
		$help = & $retVal[$i];
		$ws[] = mosHTML :: makeOption($help[0], $help[1]);
	}
	if($bid == 0)
	  $wslist = mosHTML :: selectList($ws, 'informationFrom', 'class="inputbox" size="1"',
     'value', 'text', 0 );
	else
	  $wslist = mosHTML :: selectList($ws, 'informationFrom', 'class="inputbox" size="1"',
     'value', 'text', intval($medialibrary->informationFrom));

	// выбор языка
	$retVal1 = mosMedialibraryOthers :: getLanguageArray();
	$lang = null;
	for ($i = 0, $n = count($retVal1); $i < $n; $i++)
	{
		$help = & $retVal1[$i];
		$lang[] = mosHTML :: makeOption($help[0], $help[1]);
	}
	if($bid == 0)
	  $langlist = mosHTML :: selectList($lang, 'language', 'class="inputbox" size="1"',
       'value', 'text', $medialibrary_configuration['editmedia']['default']['lang'] );
	else
	$langlist = mosHTML :: selectList($lang, 'language', 'class="inputbox" size="1"',
     'value', 'text', $media_class->language);

	// выбор рейтинга
	$retVal2 = mosMedialibraryOthers :: getRatingArray();
	$rating = null;
	for ($i = 0, $n = count($retVal2); $i < $n; $i ++)
	{
		$help = & $retVal2[$i];
		$rating[] = mosHTML :: makeOption($help[0], $help[1]);
	}
	$ratinglist = mosHTML :: selectList($rating, 'rating', 'class="inputbox" size="1"',
     'value', 'text', $media_class->rating);

	// выбор типа
	$type_list = mosMedialibraryOthers :: getTypeArray();
	$type = null;
	foreach ($type_list as $value)
	{
		$help = & $value;
		$type[] = mosHTML :: makeOption($help[0], $help[1]);
	}
	if($is_new){
    $type_list = mosHTML :: selectList($type, 'media_type', 
      'class="inputbox" size="1" onchange="type_select();" ', 'value', 'text',
      $medialibrary->media_type);
  } else{
    $type_list = mosHTML :: selectList($type, 'media_type', 
      'class="inputbox" size="1" onchange="type_select();" disabled="true"', 'value', 'text',
      $medialibrary->media_type);
  }


	// delete ebook?
	$help = str_replace($mosConfig_live_site, "", $media_class->ebookURL);
	$delete_edocument_yesno[] = mosHTML :: makeOption($help, _MEDIALIBRARY_YES);
	$delete_edocument_yesno[] = mosHTML :: makeOption('0', _MEDIALIBRARY_NO);
	$delete_edocument = mosHTML :: RadioList($delete_edocument_yesno, 'delete_edocument', 'class="inputbox"', '0', 'value', 'text');
	// fail if checked out not by 'me'
	if ($medialibrary->checked_out && $medialibrary->checked_out != $my->id)
	{
		mosRedirect("index2.php?option=$option", _MEDIALIBRARY_IS_EDITED);
	}
	if ($bid)
	{
		$medialibrary->checkout($my->id);
	}
	else
	{
		// initialise new record
		$medialibrary->published = 0;
		$medialibrary->approved = 0;
	}
	//*****************************   begin for reviews **************************//
	$database->setQuery("SELECT a.*, b.name FROM #__medialibrary_review a, #__users b".
	" WHERE a.fk_userid = b.id and a.fk_mediaid=".$bid." ORDER BY date ;");

	$reviews1 = $database->loadObjectList();

	//take review for anonymous users
	$database->setQuery("select a.*, 'anonymous' as name from #__medialibrary_review a  ".
	" WHERE a.fk_userid = 0 and a.fk_mediaid = ".$bid." ORDER BY date ;");
	$reviews2 = $database->loadObjectList();

	$reviews = array_merge($reviews1, $reviews2);

	//**********************   end for reviews   *****************************//
	$multimedia_type = 'book';
	HTML_medialibrary :: editMedia($option, $medialibrary,$media_class, $clist, $wslist, $langlist, $ratinglist, 
    $delete_edocument, $reviews, $type_list, $multimedia_type);
}
	?>





